//
//  ViewController.m
//  下载网络图片
//
//  Created by 伍银荣 on 2021/8/20.
//  Copyright © 2021 com.WYR. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic)  UIScrollView *scrollView;
@property (strong, nonatomic)  UIImageView *imgView;

@end

@implementation ViewController

//在viewDidLoad方法之前将scrollView赋值给self.view
-(void)loadView {
    //初始化scrollView
    _scrollView = [[UIScrollView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _scrollView.backgroundColor = [UIColor whiteColor];
    self.view = self.scrollView;
    
    //初始化imageView
    _imgView = [[UIImageView alloc]init];
    [self.scrollView addSubview:self.imgView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //开启一个异步线程
    NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(downloadImage) object:nil];
    [thread start];
    
    
    
}

//异步下载网络图片
- (void)downloadImage {
    //图片的地址
    NSURL *url = [NSURL URLWithString:@"http://sns-img-hw.xhscdn.com/028ff59e-5c72-36c5-9894-5b356537ef45?imageView2/2/w/540/format/jpg/q/75.jpg"];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *image = [UIImage imageWithData:data];
    
    //在主线程上更新UI(在子线程中回归主线程)
    //waitUntilDone 值为YES,会等待方法执行完毕,才会执行后续代码
    [self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
    
   
}

- (void)updateUI:(UIImage *)image {
    self.imgView.image = image;
    [self.imgView sizeToFit];
    //设置scrollView的滚动范围
    self.scrollView.contentSize = image.size;
}


@end
